import 'package:emoji_picker_flutter/emoji_picker_flutter.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'package:im_app/im/page/view/component/MessageSendPlusView.dart';
import 'package:im_app/im/page/view/component/pane/MessagePane.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

import '../../emojiOne/EmojiOne.dart';
import '../../emojiOne/EmojiPane.dart';
import '../../util/HexColor.dart';
import '../../util/ImRichTextUtil.dart';
import '../../util/PermissionUtil.dart';
import '../../util/UiUtil.dart';
import '../bloc/MessageListCubit.dart';
import '../bloc/MessageSendCubit.dart';
import '../ext/ImSpecialTextSpanBuilder.dart';
import 'component/UiUtil.dart';

class MessageSendCubitView extends StatefulWidget {

  const MessageSendCubitView({super.key});

  @override
  State<StatefulWidget> createState() => _MessageSendCubitState();
}

class _MessageSendCubitState extends State<MessageSendCubitView> {
  FocusNode userFocusNode = FocusNode();
  late TextEditingController _inputController;

  @override
  void initState() {
    _inputController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var messageSendCubit = context.watch<MessageSendCubit>();
    return Column(children: [
      Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 5, left: 5),
            child: GestureDetector(
              onTap: () => _audio(context),
              child: Icon(messageSendCubit.state.showAudio ? Icons.audiotrack_outlined : Icons.multitrack_audio_outlined),
            ),
          ),
          Expanded(
            child: messageSendCubit.state.showAudio
                ? _buildAudioNode(context)
                : _buildComposeInputText(context, messageSendCubit),
          ),
          _buildEmojiItem(messageSendCubit),

          // 更多按钮+消息发送按钮
          _buildPlusItem(messageSendCubit),
        ],
      ),
      _buildEmojiPane(context, messageSendCubit.state.showEmoji),
      _buildMorePane(messageSendCubit),
    ]);
  }

  Widget _buildEmojiItem(MessageSendCubit messageSendCubit) {
    if (messageSendCubit.state.showEmoji) {
      return Padding(
        padding: const EdgeInsets.only(right: 5, left: 5),
        child: GestureDetector(
          child: const Icon(Icons.keyboard_alt_outlined),
          onTap: () => showEmoji(context),
        ),
      );
    } else {
      return Padding(
        padding: const EdgeInsets.only(right: 5, left: 5),
        child: GestureDetector(
          child: const Icon(Icons.tag_faces_outlined),
          onTap: () => showEmoji(context),
        ),
      );
    }
  }

  Widget _buildPlusItem(MessageSendCubit messageSendCubit) {
    if (messageSendCubit.state.message == '') {
      return Padding(
        padding: const EdgeInsets.only(right: 5),
        child: GestureDetector(
          child: const Icon(Icons.add_circle_outline),
          onTap: () => showMore(context),
        ),
      );
    } else {
      return Padding(padding: const EdgeInsets.only(right: 5),
        child: GestureDetector(
        onTap: () {
          addMessage(context, messageSendCubit);
        },
        child: buildSvgView('assets/svg/send.svg', 24, 24, Colors.red),
      ),);
    }
  }

  Widget _buildEmojiPane(BuildContext context, bool showEmoji) {
    return Offstage(
      offstage: !showEmoji,
      child: EmojiPane(selectCallback: selectEmojiOneCallback, context: context,),
    );
  }

  Widget _buildMorePane(MessageSendCubit messageSendCubit) {
    bool showPlus  = messageSendCubit.state.showMore;
    var sessionId = messageSendCubit.sessionId;
    return Offstage(
      offstage: !showPlus,
      child: SizedBox(
        height: 230,
        child: MessageSendPlusView(sessionId: sessionId),
      ),
    );
  }

  Widget _buildEmojiPane2(bool showEmoji) {
    return Offstage(
      offstage: !showEmoji,
      child: SizedBox(
          height: 250,
          child: EmojiPicker(
              textEditingController: _inputController,
              config: Config(
                height: 256,
                checkPlatformCompatibility: true,
                emojiViewConfig: EmojiViewConfig(
                  emojiSizeMax: 28 * (foundation.defaultTargetPlatform == TargetPlatform.iOS ? 1.2 : 1.0),
                ),
                // swapCategoryAndBottomBar: false,
                skinToneConfig: const SkinToneConfig(),
                categoryViewConfig: const CategoryViewConfig(),
                bottomActionBarConfig: const BottomActionBarConfig(
                    enabled: false, showBackspaceButton: false, showSearchViewButton: false),
                searchViewConfig: const SearchViewConfig(),
              ))),
    );
  }

  @override
  void dispose() {
    _inputController.dispose();
    userFocusNode.dispose();
    super.dispose();
  }

  Widget _buildAudioNode(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        var isPermission = await PermissionUtil.getPermissionStatus(Permission.microphone);
        if (!isPermission) {
          UiUtil.showSnackBar(context, '录音授权失败');
          return;
        }

        var messageListCubit = context.read<MessageListCubit>();
        messageListCubit.add(MessageListShowAudioEvent(!messageListCubit.state.isAudio));
      },
      child: Container(
        decoration: const BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(5.0))),
        padding: const EdgeInsets.only(top: 13.5, bottom: 13.5),
        child: const Center(child: Text("语音 输入"),),
      ),
    );
  }

  Widget _buildComposeInputText(BuildContext context, MessageSendCubit messageSendCubit) {
    var refMessage = messageSendCubit.state.refMessage;
    if (refMessage == null) {
      return _buildInputText(context);
    }
    return Column(
      children: [
        _buildInputText(context),
        Container(
          decoration: BoxDecoration(
              color: Colors.grey.shade300,
              // border: Border.all(width: 1, color: Colors.grey),
              borderRadius: const BorderRadius.all(Radius.circular(2))),
          padding: const EdgeInsets.all(3),
          margin: const EdgeInsets.only(top: 3),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              MessageRefPane(
                message: refMessage,
                param: MessageRefParam(hasPrefix: true, maxLines: 2),
              ),
              GestureDetector(
                onTap: () {
                  messageSendCubit.add(MessageSendRefMessageEvent(null));
                },
                child: const Icon(
                  Icons.cancel_outlined,
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  Widget _buildInputText(BuildContext context) {
    var messageSendCubit = context.read<MessageSendCubit>();
    return ExtendedTextField(
        specialTextSpanBuilder: ImSpecialTextSpanBuilder(textStyle: const TextStyle(fontSize: 24)),
        focusNode: userFocusNode,
        controller: _inputController,
        decoration: InputDecoration(
            border: const OutlineInputBorder(gapPadding: 1, borderRadius: BorderRadius.all(Radius.circular(5))),
            fillColor: Colors.white,
            isCollapsed: true,
            filled: true,
            hintMaxLines: 100,
            contentPadding: const EdgeInsets.only(top: 10, right: 5, bottom: 10, left: 5),
            enabledBorder: OutlineInputBorder(
              //未选中时候的颜色
              gapPadding: 4,
              borderRadius: BorderRadius.circular(5.0),
              borderSide: const BorderSide(
                color: Colors.white,
              ),
            ),
            focusedBorder: OutlineInputBorder(
              //选中时外边框颜色
              gapPadding: 4,
              borderRadius: BorderRadius.circular(5.0),
              borderSide: const BorderSide(
                color: Colors.white,
              ),
            )
        ),
        //maxLength: 30,//最大长度，设置此项会让TextField右下角有一个输入数量的统计字符串
        maxLines: null,
        //最大行数
        autocorrect: true,
        //是否自动更正
        autofocus: false,
        //是否自动对焦
        obscureText: false,
        //是否是密码
        textAlign: TextAlign.left,
        //文本对齐方式
        style: const TextStyle(fontSize: 18.0, color: Colors.black),
        //输入文本的样式
        //inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],//允许的输入格式
        onChanged: (text) {
          messageSendCubit.add(MessageSendMessageEvent(text));
        },
        onEditingComplete: () {
          print('test');
        },
        onSubmitted: (text) {
          //内容提交(按回车)的回调
          messageSendCubit.add(MessageSendSendMessageEvent(text, null));
          _inputController.text = "";
          print('submit $text');
        },
        enabled: true,
        //是否禁用
        extendedContextMenuBuilder: (BuildContext context, ExtendedEditableTextState editableTextState) {
          return AdaptiveTextSelectionToolbar.buttonItems(
            buttonItems: [
              ContextMenuButtonItem(
                  onPressed: () {
                    editableTextState.pasteText(SelectionChangedCause.toolbar);
                  },
                  label: '粘贴',
                  type: ContextMenuButtonType.custom),
            ],
            anchors: editableTextState.contextMenuAnchors,
          );
        });
  }

  Widget buildInputText2(BuildContext context, TextEditingController controller) {
    var messageSendCubit = context.read<MessageSendCubit>();
    return TextField(
      focusNode: userFocusNode,
      controller: controller,
      decoration: InputDecoration(
          border: const OutlineInputBorder(gapPadding: 1, borderRadius: BorderRadius.all(Radius.circular(5))),
          fillColor: Colors.white,
          filled: true,
          hintMaxLines: 100,
          contentPadding: const EdgeInsets.only(top: 10, right: 5, bottom: 10, left: 5),
          enabledBorder: OutlineInputBorder(
            //未选中时候的颜色
            gapPadding: 1,
            borderRadius: BorderRadius.circular(5.0),
            borderSide: const BorderSide(
              color: Colors.white,
            ),
          ),
          focusedBorder: OutlineInputBorder(
            //选中时外边框颜色
            gapPadding: 1,
            borderRadius: BorderRadius.circular(5.0),
            borderSide: const BorderSide(
              color: Colors.white,
            ),
          )),
      //maxLength: 30,//最大长度，设置此项会让TextField右下角有一个输入数量的统计字符串
      maxLines: null,
      //最大行数
      autocorrect: true,
      //是否自动更正
      autofocus: false,
      //是否自动对焦
      obscureText: false,
      //是否是密码
      textAlign: TextAlign.left,
      //文本对齐方式
      style: TextStyle(fontSize: 18.0, color: Colors.black),
      //输入文本的样式
      //inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],//允许的输入格式
      onChanged: (text) {
        //内容改变的回调
        messageSendCubit.add(MessageSendMessageEvent(text));
      },
      onEditingComplete: () {
        print('test');
      },
      onSubmitted: (text) {
        //内容提交(按回车)的回调
        messageSendCubit.add(MessageSendSendMessageEvent(text, null));
        _inputController.text = "";
        controller.text = '';
        print('submit $text');
      },
      enabled: true, //是否禁用
    );
  }

  String buildMessage(Map<String, dynamic> message) {
    var codepoint = int.parse("1f600", radix: 16);
    print("codepoint: $codepoint");
    String unicodeString = String.fromCharCode(codepoint);
    return unicodeString;
  }

  Future<void> addMessage(BuildContext context, MessageSendCubit messageSendCubit) async {
    if (messageSendCubit.state.showAudio) return;
    String text = _inputController.text.trim();
    if (text == '') return;
    _inputController.text = '';
    messageSendCubit.add(MessageSendSendMessageEvent(text, null));
  }

  void _audio(BuildContext context) {
    var messageSendCubit = context.read<MessageSendCubit>();
    messageSendCubit.add(MessageSendShowAudioEvent(!messageSendCubit.state.showAudio));
  }

  void showEmoji(BuildContext context) {
    var messageSendCubit = context.read<MessageSendCubit>();
    messageSendCubit.add(MessageSendShowEmojiEvent(!messageSendCubit.state.showEmoji));
    FocusScope.of(context).unfocus();
  }

  void showMore(BuildContext context) {
    var messageSendCubit = context.read<MessageSendCubit>();
    messageSendCubit.add(MessageSendShowMoreEvent(!messageSendCubit.state.showMore));
    FocusScope.of(context).unfocus();
  }

  void hideEmoji(BuildContext context) {
    var messageSendCubit = context.read<MessageSendCubit>();
    messageSendCubit.hideEmoji();

    FocusScope.of(context).unfocus();
    print("unfocus!!!!!!!!!!!!!!!!");
  }

  selectEmojiOneCallback(BuildContext context, EmojiOne emojiOne) {
    print("emojiOne: ${emojiOne.emojiPath}");
    _inputController.text = _inputController.text + ImRichTextUtil.emojiToString(emojiOne);

    var messageSendCubit = context.read<MessageSendCubit>();
    messageSendCubit.add(MessageSendMessageEvent(_inputController.text));
  }
}
